import os, subprocess, platform, tempfile, sys, random, time, tarfile, zipfile
from pathlib import Path
from json import loads, dumps
print ("Checking for required packages...")
time.sleep(0.8)
Platform = platform.system()
requirements = "colorama requests tqdm"
dist_folder = os.path.join(Path.home(),".shadowsocks")
try: 
    import requests, colorama, tqdm
    colorama.init(autoreset=True)
    print(colorama.Fore.GREEN + "Armed, aren' yah?")
    time.sleep(0.8)
except:
    print("Well, we have to do it ourselves...\n *rolling sleeves up*")
    time.sleep(0.8)
    try:
        import pip
    except:
        try:
            subprocess.run(["python", "-m", "ensurepip", "--upgrade"], check = True, shell=True) if Platform == "Windows" else subprocess.run([f"python3 -m ensurepip --upgrade"], check = True, shell=True)
        except Exception as err:
            print(f"Oops, take this error : {err}")
            exit()
    subprocess.run(["python", "-m", "pip", "install"] + requirements.split(" "), check = True, shell=True) if Platform == "Windows" else subprocess.run([f"python -m pip install {requirements}"], check = True, shell=True)
    import colorama, requests, tqdm
    colorama.init(autoreset=True)
    print(colorama.Fore.GREEN + "Picked up Jarvis and guns Cap.")
    time.sleep(0.8)
if Platform == "Darwin":
    print(colorama.Fore.RED + "Sorry my dude, but beware that this script will NOT work on MacOS. Tweak it or install yourself, I don't own any MacOS device to test.")
    exit()
typing_speed = 73 #wpm
def type_slowly(text, color):
    for i in text:
        sys.stdout.write(color + i)
        sys.stdout.flush()
        sleep = random.random()*10.0/typing_speed
        if i in (",", ".", "\n", "?", "("):
            sleep =+ 0.4
        time.sleep(sleep)
text = """
Before we start, I'd like you to know why I wrote this script (you probably know, anyways). First of all, for myself. To do the unmetnionable crime, that most likely you also seek.
To bypass the restrictions creatures less than animals have set on us. Restrictions that don't seem to apply on their sordid selves.
"For the embarrassment due to empty pockets
For the yearning for a normal life
For the dreams of the dumpster diving kids"
For the bullets, left eternal scars on the sane and body, of talents, at Sharif university.
For Nika Shakarami, the 17 years old girl, who was kidnapped, raped, tortured. She died in hopelessness in an unknown place. And even after she left this world in the best years of her life, they took her body parts out and stitched her from her chest to her stomach!
See? They even didn't allow a funreal. Burred her in a recluse and far-off village. 
Can you imagine what she suffered? Now try to imagine how her family and boyfriend feel, they made them do a forced confess that she died beacuase of falling of a roof.
For the hundreds of Mahsa's and Nika's whose name never came in history.
For the massacre of Zahedan that is going on. And no media seems to notice.
For women, life, """
if "y" in input("Would you like to hear/read some words from the author of this script? Wouldn't take more than 5 minutes. Type Y(or y) for yes if you wish, or type anything else (or just press enter) to continue the installation : ").lower():
    type_slowly(text,colorama.Back.RED)
    for i in "free":
        sys.stdout.write( colorama.Back.WHITE + colorama.Fore.GREEN + i)
        sys.stdout.flush()
        sleep = random.random()*10.0/typing_speed
        if i in (",", ".", "\n", "?", "("):
            sleep =+ 0.4
        time.sleep(sleep)
    for i in "dom":
        sys.stdout.write(colorama.Back.WHITE + colorama.Fore.RED + i)
        sys.stdout.flush()
        sleep = random.random()*10.0/typing_speed
        if i in (",", ".", "\n", "?", "("):
            sleep =+ 0.4
        time.sleep(sleep)
    print("")
time.sleep(1)
print(colorama.Back.GREEN + "Finding the latest version of shadowsocks-rust...")
try:
    releases = requests.get("https://api.github.com/repos/shadowsocks/shadowsocks-rust/releases")
    data = releases.json()
    if Platform == "Linux":
        latest_stable_release = requests.get(next(x for x in next(x for x in data if not "alpha" in x["html_url"])["assets"] if "x86_64-unknown-linux-gnu" in x["name"])["url"]).json()
    elif Platform == "Windows":
        latest_stable_release = requests.get(next(x for x in next(x for x in data if not "alpha" in x["html_url"])["assets"] if "x86_64-pc-windows-msvc" in x["name"])["url"]).json()
except Exception as err:
    print(colorama.Fore.RED + f"Oops, take this error : {err}")
    exit()
print(colorama.Fore.GREEN + "Done sir. Chose " + latest_stable_release["name"] + "\n" + colorama.Fore.RESET + colorama.Back.GREEN + " Downloading...")
try:
    shadowsocks_archive = os.path.join(tempfile.gettempdir(), latest_stable_release["name"])
    if  not os.path.exists(shadowsocks_archive):
        file = requests.get(latest_stable_release["browser_download_url"], stream=True)
        progress_bar = tqdm.tqdm(total=int(file.headers.get('content-length', 0)), unit=" iB")
        with open(shadowsocks_archive, "wb") as handle:
            for data in file.iter_content(1024):
                progress_bar.update(len(data))
                handle.write(data)
        progress_bar.close()
    else:
        print(colorama.Fore.GREEN + "Hmm... It's already downloaded?")
except Exception as err:
    print(colorama.Fore.RED + f"Oops, take this error : {err}")
    exit()

print(colorama.Fore.GREEN + "Done Cheif.\n " + colorama.Fore.RESET + colorama.Back.GREEN + " Let's find the best version of v2ray-plugin")
try:
    releases = requests.get("https://api.github.com/repos/teddysun/v2ray-plugin/releases")
    data = releases.json()
    if Platform == "Linux":
        latest_stable_release = requests.get(next(x for x in data[0]["assets"] if "linux-amd64" in x["name"])["url"]).json()
    elif Platform == "Windows":
        latest_stable_release = requests.get(next(x for x in data[0]["assets"] if "windows-amd64" in x["name"])["url"]).json()
except Exception as err:
    print(colorama.Fore.RED + f"Oops, take this error : {err}")
    exit()
print(colorama.Fore.GREEN + "Done! I chose " + latest_stable_release["name"] + ".\n" + colorama.Fore.RESET + colorama.Back.GREEN + "Let's download the thing...")
try:
    v2ray_archive = os.path.join(tempfile.gettempdir(), latest_stable_release["name"])
    if not os.path.exists(v2ray_archive):
        file = requests.get(latest_stable_release["browser_download_url"], stream=True)
        progress_bar = tqdm.tqdm(total=int(file.headers.get('content-length', 0)), unit=" iB")
        with open(v2ray_archive, "wb") as handle:
            for data in file.iter_content(1024):
                progress_bar.update(len(data))
                handle.write(data)
        progress_bar.close()
    else:
        print(colorama.Fore.GREEN + "Hmm... It's already downloaded?")
except Exception as err:
    print(colorama.Fore.RED + f"Oops, take this error : {err}")
    exit()
print(colorama.Fore.GREEN + "DONE!\n " + colorama.Fore.RESET + colorama.Back.GREEN +  "Let's unpack these packets (Your today dose of dad-like jokes)")
try:
    if not os.path.exists(dist_folder):
        os.mkdir(dist_folder)
    if not "zip" in shadowsocks_archive:
        with tarfile.open(shadowsocks_archive) as f:
            f.extractall(dist_folder)
    else:
        with zipfile.ZipFile(shadowsocks_archive) as zip_ref:
            zip_ref.extractall(dist_folder)
    if not "zip" in v2ray_archive:
        with tarfile.open(v2ray_archive) as f:
            f.extractall(dist_folder)
    else:
        with zipfile.ZipFile(v2ray_archive) as zip_ref:
            zip_ref.extractall(dist_folder)
    v2ray_file = next(x for x in os.listdir(dist_folder) if "v2ray" in x)
    os.rename(os.path.join(dist_folder, v2ray_file), os.path.join(dist_folder,"v2ray-plugin" if Platform == "Linux" else "v2ray-plugin.exe") ) 
except Exception as err:
    print(colorama.Fore.RED + f"Oops, take this error : {err}")
    exit()

print(colorama.Fore.GREEN + "Did it.\n " + colorama.Fore.RESET + colorama.Back.GREEN +  "Adding to PATH...")
try:
    path = os.getenv("PATH")
    if not "shadowsocks" in path:
        if Platform == "Windows":
            os.system(f'setx PATH "%PATH%;{dist_folder}"')
        elif Platform == "Linux":
            if "bash" in os.getenv("SHELL") :
                with open(os.path.join(Path.home(),".bashrc"), "a") as f:
                    f.write (f"\nexport PATH=$PATH:{dist_folder}")
            if "zsh" in os.getenv("SHELL") :
                with open(os.path.join(Path.home(),".zshrc"), "a") as f:
                    f.write (f"\nexport PATH=$PATH:{dist_folder}")
    else:
        print(colorama.Fore.GREEN + "Already in PATH.")
except Exception as err:
    print(colorama.Fore.RED + f"Oops, take this error : {err}")
    exit()
print(colorama.Fore.GREEN + "*Sigh*, done.\n " + colorama.Fore.RESET + colorama.Back.GREEN +  "Starting config...")
try:
    shadowsocks_link = input("""For sure you have a shadowsocks link?\n If you don't have, check "internet4iran" channel in telegram and pick the android link.\n Enter your link here : """)
    if Platform == "Linux":
        config = subprocess.run([os.path.join(dist_folder,"ssurl"),"-d" ,shadowsocks_link], stdout=subprocess.PIPE).stdout.decode('utf-8')
    elif Platform == "Windows":
        config = subprocess.run([os.path.join(dist_folder,"ssurl.exe"),"-d" ,shadowsocks_link], stdout=subprocess.PIPE).stdout.decode('utf-8')
    config = loads(config)
    config["local_address"] = "127.0.0.1"
    config["local_port"] = 8118
    config["protocol"] = "http"
    config = dumps(config)
    with open(os.path.join(dist_folder,"config.json"), "w") as f:
        f.write(config)
    if Platform  == "Windows":
        with open(os.path.join(dist_folder,"shadowsocks.cmd"),"w") as f:
            f.write(f"sslocal -c {os.path.join(dist_folder,'config.json')}")
    elif Platform == "Linux":
        with open(os.path.join(dist_folder,"shadowsocks"), "w") as f:
            f.write(f"#!/usr/bin/env bash\nsslocal -c {os.path.join(dist_folder,'config.json')}")
        subprocess.run([f"chmod +x {os.path.join(dist_folder,'shadowsocks')}"], check = True, shell=True)
            
except Exception as err:
    print(colorama.Fore.RED + f"Oops, take this error : {err}")
    exit()
type_slowly("We've come so far Cheif.\n Done so many evils...\n You might even do not have a clue, of what have I done, me, Pythana.\n Anyways, there are more to do, whenever you wanted to escape the (fire)walls of this prison, type shadowsocks in CMD(or RUN, in WINDOWS) or terminal, and point your proxy to http://127.0.0.1:8118.\n With the hope of the bests, Nerlock Golpes", colorama.Fore.GREEN)










 
